package com.z.blog.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.z.base.vo.PageVo;
import com.z.base.web.BaseController;
import com.z.blog.entity.Comment;
import com.z.blog.entity.User;
import com.z.blog.service.ICommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * 评论实体Controller
 *
 * @author jmys
 * @date 2022-09-01
 */
@Controller
@RequestMapping("/blog/comment")
public class CommentController extends BaseController {


    @Autowired
    private ICommentService commentService;
    @GetMapping("/{blogId}")
    public String comments(@PathVariable Long blogId, Comment comment, PageVo pageVo, Model model) {
        comment.setParentCommentId(-1L);
        comment.setNickname("");
        model.addAttribute("comments",
                commentService.selectCommentPage(comment, pageVo).getList());
        return "blog/read :: commentList";
    }


    @PostMapping("/post")
    public String post(Comment comment, HttpSession session) {

        if(StringUtils.isNotEmpty(comment.getContent())){
            User user = (User) session.getAttribute("user");
            if (user != null) {
                comment.setAvatar(user.getAvatar());
                comment.setAdminComment(true);
            }else {
                comment.setAdminComment(false);
            }
            comment.setCreateTime(new Date());
            commentService.save(comment);
        }

        return "redirect:/blog/comment/" + comment.getBlogId();
    }
}
